import { WithSpringConfig, WithTimingConfig, withTiming, withSpring, AnimationCallback } from 'react-native-reanimated';
import { ANIMATION_CONFIGS, ANIMATION_METHOD } from '../constants';

interface AnimateParams {
  point: number;
  velocity?: number;
  configs?: WithSpringConfig | WithTimingConfig;
  onComplete?: AnimationCallback;
}

type AnimationResult = ReturnType<typeof withTiming> | ReturnType<typeof withSpring>;

export const animate = ({ point, configs = undefined, velocity = 0, onComplete }: AnimateParams): AnimationResult => {
  'worklet';

  let finalConfigs = configs;
  if (!finalConfigs || typeof finalConfigs !== 'object' || finalConfigs === null) {
    finalConfigs = ANIMATION_CONFIGS;
  }

  let type = ANIMATION_METHOD.SPRING; 

  if (finalConfigs && typeof finalConfigs === 'object' && finalConfigs !== null) {
    const hasDuration = (finalConfigs as WithTimingConfig).duration !== undefined;
    const hasEasing = (finalConfigs as WithTimingConfig).easing !== undefined;

    if (hasDuration || hasEasing) {
      type = ANIMATION_METHOD.TIMING;
    }
  }

  if (type === ANIMATION_METHOD.TIMING) {
    return withTiming(point, finalConfigs as WithTimingConfig, onComplete);
  } else {
    return withSpring(point, Object.assign({ velocity }, finalConfigs) as WithSpringConfig, onComplete);
  }
};
